<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2008 Starbugs <univis2typo3@googlegroups.com>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/

require_once(PATH_tslib.'class.tslib_pibase.php');
require_once PATH_typo3conf.'ext/univis2typo3/pi2/class.tx_univis2typo3_pi2.php';

/**
 * Plugin 'projects' for the 'univis2typo3' extension.
 *
 * @author	Starbugs <univis2typo3@googlegroups.com>
 * @package	TYPO3
 * @subpackage	tx_univis2typo3
 */
class tx_univis2typo3_pi3 extends tslib_pibase {
	var $prefixId      = 'tx_univis2typo3_pi3';		// Same as class name
	var $scriptRelPath = 'pi3/class.tx_univis2typo3_pi3.php';	// Path to this script relative to the extension dir.
	var $extKey        = 'univis2typo3';	// The extension key.
	var $pi_checkCHash = true;
	var $department    = '';
	/**
	 * The main method of the PlugIn
	 *
	 * @param	string		$content: The PlugIn content
	 * @param	array		$conf: The PlugIn configuration
	 * @return	The content that is displayed on the website
	 */
	function main($content,$conf)	{
		$this->conf=$conf;
		$this->pi_setPiVarDefaults();
		$this->pi_loadLL();

		$this->department = $this->conf['department_id'];

		$templateCode = $this->cObj->fileResource($this->conf['templateFile']);
		$this->template = $this->cObj->getSubpart($templateCode,"###TEMPLATE_NEW_PROJECT###");
	
		$this->pi_initPIflexForm();
		
		$ids = explode(",", $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'what_to_display', 'sDEF'));
		$content = $this->getContent($ids);
		
		return $this->pi_wrapInBaseClass($content);
	}
	
	function getPersons($userIds) {
		$select 	= 'uid AS uid,
					   realName AS name,
					   tx_univis2typo3_image AS image,
					   tx_univis2typo3_person_key as univisKey,
					   url AS url';
		$from		= 'be_users 
						JOIN u_person_location ON u_person_location.person_key = be_users.tx_univis2typo3_person_key';
		$where		= '';
		foreach($userIds as $id)
			$where .= 'be_users.tx_univis2typo3_person_key = "' . $id . '" OR ';
		$where .= 'be_users.tx_univis2typo3_person_key = "' . $id.'"';
		$groupby	= '';
		$orderby	= '';
		$limit 		= '';
		
		$query = $GLOBALS['TYPO3_DB']->SELECTquery(
			$select,
			$from,
			$where,
			$groupby,
			$orderby,
			$limit
		);

		return $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
	}
	
	function getProject($projectKey = '', $authorKey = '', $maxNumber = 0)
	{
		$selection		= "DISTINCT 
  								T1.title, T1.title_en, T1.description, T1.description_en,
  								GROUP_CONCAT(DISTINCT T2.coworker SEPARATOR ', ') AS coworkers,
  								GROUP_CONCAT(DISTINCT T3.public SEPARATOR ', ') AS publications,
  								GROUP_CONCAT(DISTINCT T4.director SEPARATOR ', ') AS directors,
								T1.url, T1.url_en,
  								GROUP_CONCAT(DISTINCT T5.name SEPARATOR ', ') AS externalName,
  								GROUP_CONCAT(DISTINCT T5.url SEPARATOR ', ') AS externalURL,
  								GROUP_CONCAT(DISTINCT T6.name SEPARATOR ', ') AS promoterName,
  								GROUP_CONCAT(DISTINCT T6.url SEPARATOR ', ') AS promoterURL";
		$from 			= "	`tx_u2t3_research` AS T1
							LEFT OUTER JOIN u_research_coworkers AS T2 ON T1.`key` = T2.`project_key` 
							LEFT OUTER JOIN u_research_directors AS T4 ON T1.`key` = T4.`project_key` 
							LEFT OUTER JOIN u_research_publics AS T3 ON T1.`key` = T3.`project_key` 
							LEFT OUTER JOIN u_research_externals AS T5 ON T1.`key` = T5.`project_key` 
							LEFT OUTER JOIN u_research_promoters AS T6 ON T1.`key` = T6.`project_key`";

		$whereArr = array();
		if ('' != $projectKey) {
		    $whereArr[] = "`uid` = ".$projectKey;
		}
		if ('' != $authorKey) {
		    $whereArr[] = "(`T2`.`coworker` = '{$authorKey}' OR `T4`.`director` = '{$authorKey}')";
		}
		$where = implode(' AND ', $whereArr);
		$groupby		= '`T1`.`key`';
		$orderby		= '';
		$limit 			= '';
		if ($maxNumber > 0) {
		    $limit = $maxNumber;
		}

		$query = $GLOBALS['TYPO3_DB']->SELECTquery(
		$selection,   	// SELECT
		$from,		// FROM
		$where,		// WHERE
		$groupby,	// GROUP BY
		$orderby,	// ORDER BY
		$limit		// LIMIT
		);

		$res = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
		$out = array ();
		if (mysql_num_rows($res) == 0)
				return $out;

		while ($row = mysql_fetch_assoc($res))
		{
			$out[] = $row;
		}

		/* Return complete array of arrays */
		return $out;
	}
	
	function getNitems($authorKey = '', $maxNumber){
	    return $this->getProjects($authorKey, $maxNumber);
	}

	function getProjects($authorKey, $maxNumber = 0){
	    return $this->getProject('', $authorKey, $maxNumber);
	}

	function getContent($userIds) {
		$projectItems = $this->getProject($userIds[0]);
		$projectItems = $projectItems[0];
		$arrMarker = array();
		$arrWrappedProjectSubpart = array();
		
		$projectDescription = $this->parseContent($projectItems['description']);
		$arrMarker['###TEMPLATE_PROJECT_DESCRIPTION###'] = $projectDescription;
		
		// get contributors
		$content = '';
		$coworkers = array();
		$coworkers = explode(", ", $projectItems['coworkers']);
		$personItems = $this->getPersons($coworkers);

		while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($personItems)) {
			$arrMarker['###IMAGE###'] = $row['image'];
			$arrMarker['###NAME###'] = $row['name'];
			$arrMarker['###URL###'] = $row['url'];
			
			$content .= $this->cObj->substituteMarkerArrayCached(
			    $this->cObj->getSubpart($this->template,"###TEMPLATE_NEW_PROJECT_CONTRIBUTORS###"),
			    $arrMarker);			    
		}
		$arrWrappedProjectSubpart['###TEMPLATE_NEW_PROJECT_CONTRIBUTORS###'] = $content;

		// get publications
		$content = '';		
		$publications = array();
		$publications = explode(", ", $projectItems['publications']);

		$publicationsObj = t3lib_div::makeInstance("tx_univis2typo3_pi2");
		$publicationsObj->cObj = $this->cObj;
		$publicationsObj->department = $this->conf['department_id'];

		$publicationItems = $publicationsObj->getPublications($publications);
		
		while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($publicationItems)) {
			$arrMarker['###TEMPLATE_PROJECT_PUBLICATIONS###'] = $row['pubtitle'];
		        $arrMarker['###TEMPLATE_PROJECT_PUBLICATIONS_PDF_DOWNLOAD###'] = ('' == $row['puburl'])
		        ? ''
			: '<a href="'.$row['puburl'].'" target="_blank">'
			    . '<img src="http://www5.informatik.uni-erlangen.de/images/fileicon-pdf.png" alt="PDF download" width="12" height="12" />'
			    . '</a>';
		
			$content .= $this->cObj->substituteMarkerArrayCached(
			    $this->cObj->getSubpart($this->template,"###TEMPLATE_NEW_PROJECT_PUBLICATION###"),
			    $arrMarker);			    
		}
		$arrWrappedProjectSubpart['###TEMPLATE_NEW_PROJECT_PUBLICATION###'] .= $content;
	
		return $this->cObj->substituteMarkerArrayCached(
					$this->template,
					$arrMarker,
					$arrWrappedProjectSubpart);
	}
	
	function parseContent($content)
	{
		$pattern = '/\* *([^*]*) *\*/';
		$ersetzung = '<h3>${1}</h3>';
		$content = preg_replace($pattern,$ersetzung,$content);

		return $content;
	}
	
}



if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/univis2typo3/pi3/class.tx_univis2typo3_pi3.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/univis2typo3/pi3/class.tx_univis2typo3_pi3.php']);
}

?>
